const arr = [
  { id: 1, name: '部门1', pid: 0 },
  { id: 2, name: '部门2', pid: 1 },
  { id: 3, name: '部门3', pid: 1 },
  { id: 4, name: '部门4', pid: 3 },
  { id: 5, name: '部门5', pid: 4 },
];

function arrToTree(array) {
  const itemMap = {};
  let rootId = 0;

  array.forEach((item) => {
    const { id, pid } = item;
    if (!itemMap[id]) {
      itemMap[id] = {
        children: [],
      }
    }
    itemMap[id] = { ...item, children: itemMap[id].children };
    if (pid === 0) {
      rootId = id;
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = { children: [] };
      }
      itemMap[pid].children.push(itemMap[id]);
    }
  });

  console.log(itemMap);
  return itemMap[rootId];
}